//
//  ZYCTeaLeaveApplicationViewController.m
//  ZDSC
//
//  Created by 张威 on 2021/10/19.
//

#import "ZYCTeaLeaveApplicationViewController.h"
#import "ZYCTeaLeaveRequiredCell.h"
#import "ZYCTeaLeaveOptionalCell.h"
#import "ZYCTeaLeaveAddPhotoCell.h"
#import "ZYCTeaLeaveApplicationBottomView.h"
#import "ZYCTeaLeaveRecordFlowChartView.h"
#import "ZYCCommonBaseModel.h"
#import "ZYCCommonSelectObjectPickerView.h"
#import <TZImagePickerController.h>
#import "ZYCTeaLeaveFlowChartModel.h"
#import "ZYCTeaLeaveApproverViewController.h"
#import "ZYCFileCommonModel.h"
#import "ZYCSelectAmPmDateView.h"
#import "NSString+File.h"
#import <MobileCoreServices/MobileCoreServices.h>

@interface ZYCTeaLeaveApplicationViewController ()<UITableViewDelegate,UITableViewDataSource,ZYCCommonSelectObjectPickerViewDelegate,TZImagePickerControllerDelegate,ZYCTeaLeaveAddPhotoCellDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,ZYCTeaLeaveRecordFlowChartViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *dataSource;
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;

@property (nonatomic, strong) ZYCTeaLeaveRecordFlowChartView *flowChartView;
@property (nonatomic, strong) ZYCTeaLeaveApplicationBottomView *bottomView;

// 所属部门

@property (nonatomic, strong) ZYCCommonSelectObjectPickerView *deptPickerView;
@property (nonatomic, strong) NSArray *deptArray;
// 所属岗位
@property (nonatomic, strong) ZYCCommonSelectObjectPickerView *postPickerView;
@property (nonatomic, strong) NSArray *postArray;

// 请假类型
@property (nonatomic, strong) ZYCCommonSelectObjectPickerView *leaveTypePickerView;
@property (nonatomic, strong) NSArray *leaveTypeArray;

// 开始时间
@property (nonatomic, strong) ZYCSelectAmPmDateView *startDatePickerView;
// 结束时间
@property (nonatomic, strong) ZYCSelectAmPmDateView *endDatePickerView;



@property (nonatomic, strong) NSMutableArray * selectedPhotos;
@property (nonatomic, strong) NSMutableArray * selectedAssets;

@property (nonatomic, assign) NSUInteger updateImageCount;
@property (nonatomic, strong) NSMutableArray <ZYCFileCommonModel *>*updateImageResults;

@property (strong, nonatomic) CLLocation *location;


/** 部门id*/
@property (nonatomic, copy) NSString *deptId;
/** 部门名称*/
@property (nonatomic, copy) NSString *deptName;
/** 岗位id*/
@property (nonatomic, copy) NSString *postId;
/** 岗位名称*/
@property (nonatomic, copy) NSString *postName;
/** 请假类型id*/
@property (nonatomic, copy) NSString *leaveTypeId;
/** 请假类型*/
@property (nonatomic, copy) NSString *leaveType;
/**开始时间*/
@property (nonatomic, copy) NSString *leaveStartTime;
/** 结束时间*/
@property (nonatomic, copy) NSString *leaveEndTime;
/** 请假天数*/
@property (nonatomic, copy) NSString *leaveDays;
/** 请假理由*/
@property (nonatomic, copy) NSString *leaveReason;
/** 下一节点审批人（多个用逗号隔开）*/
@property (nonatomic, strong) NSMutableArray *toUsers;

/** 流程定义key */
@property (nonatomic, copy) NSString *processDefinitionKey;
/** 抄送人 */
@property (nonatomic, strong) NSArray *copyUsers;

@property (nonatomic, strong) NSDateFormatter *dateFormatter;


@property (nonatomic, strong) NSArray *footerDataSource;


@end

@implementation ZYCTeaLeaveApplicationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"请假申请";
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.bottomView];
    self.tableView.tableFooterView = self.flowChartView;
    

    
    // 获取所属部门
    [self getDeptList];
    // 获取请假类型
    [self getLeaveTypeArray];
}




#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZYCWeakSelf
    if (indexPath.section == 6) {// 请假事由
        ZYCTeaLeaveOptionalCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZYCTeaLeaveOptionalCell class]) forIndexPath:indexPath];
        NSDictionary *dict = self.dataSource[indexPath.section];
        cell.titleString = dict[@"title"];
        cell.placeHolderString = dict[@"placeHolder"];
        cell.textEditEndBlock = ^(NSString * _Nonnull text) {
            weakSelf.leaveReason = text;
        };
        return cell;
    }else if(indexPath.section == 7){// 上传图片
        ZYCTeaLeaveAddPhotoCell *cell = [ZYCTeaLeaveAddPhotoCell teacherLeaveAddPhotoCellWithType:ZYCTeaLeaveAddPhotoTypeAdd TableView:tableView];
        NSDictionary *dict = self.dataSource[indexPath.section];
        cell.titleString = dict[@"title"];
        cell.dataSource =  self.selectedPhotos;
        cell.selectedAssets = self.selectedAssets;
        cell.delegate = self;
        return cell;
    }
    ZYCTeaLeaveRequiredCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZYCTeaLeaveRequiredCell class]) forIndexPath:indexPath];
    NSDictionary *dict = self.dataSource[indexPath.section];
    cell.titleString = dict[@"title"];
    cell.placeHolderString = dict[@"placeHolder"];
    switch (indexPath.section) {
        case 0:{// 所属部门
            cell.contentString = self.deptName;
            break;
        }
        case 1:{// 所属岗位
            cell.contentString = self.postName;
            break;
        }
        case 2:{// 请假类型
            cell.contentString = self.leaveType;
            break;
        }
        case 3:{// 开始时间
            cell.contentString = self.leaveStartTime;
            break;
        }
        case 4:{// 结束时间
            cell.contentString = self.leaveEndTime;
            break;
        }
        case 5:{// 请假时长
            cell.contentString = self.leaveDays;
            break;
        }
        case 6:{ // 请假事由
            cell.contentString = self.leaveReason;
            break;
        }
        default:
            break;
    }
    return cell;
}

-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 10.0f;
    }
    return 5.0f;
}

-(CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 6 || indexPath.section == 7) {
        return 150.0f;
    }
    return 55.0f;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self handlerTableViewSelect:indexPath];
}

- (void)handlerTableViewSelect:(NSIndexPath *)indexPath{
    switch (indexPath.section) {
        case 0:{
            if (self.deptArray.count == 0) {
                [MrjToast makeToast:@"暂无所属部门" makeView:self.view];
                return;
            }
            [self.deptPickerView show];
        }
            break;
        case 1:{
            if (self.deptName.length == 0) {
                [MrjToast makeToast:@"请选择部门" makeView:self.view];
                return;
            }
            
            if (self.postArray.count == 0) {
                [MrjToast makeToast:@"请部门下无岗位" makeView:self.view];
                return;
            }
            [self.postPickerView show];
        }
            break;
        case 2:{
            [self.leaveTypePickerView show];
        }
            break;
        case 3:{

            [self.startDatePickerView show];
        }
            break;
        case 4:{
            if (self.leaveStartTime.length == 0) {
                [MrjToast makeToast:@"请选择开始时间" makeView:self.view];
                return;
            }
            [self.endDatePickerView show];
        }
            break;
        default:
            break;
    }
}

#pragma mark - ZYCTeaLeaveAddPhotoCellDelegate
- (void)teaLeaveAddPhoto{
    [self presentFliter];
    
}
- (void)presentFliter{
    ZYCWeakSelf
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self takePhoto];
    }];
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf pushTZImagePickerViewController];

    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf dismissViewControllerAnimated:YES completion:nil];
    }];
    [alert addAction:photoAction];
    [alert addAction:albumAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)takePhoto{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        // 无相机权限 做一个友好的提示
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self takePhoto];
                });
            }
        }];
        // 拍照之前还需要检查相册权限
    } else if ([PHPhotoLibrary authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    } else if ([PHPhotoLibrary authorizationStatus] == 0) { // 未请求过相册权限
        [[TZImageManager manager] requestAuthorizationWithCompletion:^{
            [self takePhoto];
        }];
    } else {
        [self pushImagePickerController];
    }

}
// 调用相机
- (void)pushImagePickerController {
    // 提前定位
    __weak typeof(self) weakSelf = self;
    [[TZLocationManager manager] startLocationWithSuccessBlock:^(NSArray<CLLocation *> *locations) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf.location = [locations firstObject];
    } failureBlock:^(NSError *error) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf.location = nil;
    }];
    
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        self.imagePickerVc.sourceType = sourceType;
        NSMutableArray *mediaTypes = [NSMutableArray array];
        [mediaTypes addObject:(NSString *)kUTTypeImage];
        if (mediaTypes.count) {
            _imagePickerVc.mediaTypes = mediaTypes;
        }
        [self presentViewController:_imagePickerVc animated:YES completion:nil];
    } else {
        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}

#pragma mark - ZYCCommonSelectObjectPickerViewDelegate
- (void)selectObjectPickerView:(ZYCCommonSelectObjectPickerView *)pickerView DidClickModel:(ZYCCommonBaseModel *)model{
    if (pickerView == self.deptPickerView) {//部门选择器
        self.deptName = model.name;
        self.deptId = model.nameId;
        NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:0];
        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
        [self getPostListByDeptId:self.deptId];
        
        self.postName = @"";
        NSIndexSet *indexSet1 = [[NSIndexSet alloc]initWithIndex:1];
        [self.tableView reloadSections:indexSet1 withRowAnimation:UITableViewRowAnimationNone];
        
    }else  if (pickerView == self.postPickerView) {// 岗位选择器
        self.postName = model.name;
        self.postId = model.nameId;
        NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:1];
        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
    }else  if (pickerView == self.leaveTypePickerView) {// 请假类型选择器
        self.leaveType = model.name;
        self.leaveTypeId = model.nameId;
        NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:2];
        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];

    }
}

#pragma mark - ZYCTeaLeaveRecordFlowChartViewDelegate
// 选择审批人
- (void)teaLeaveRecordFlowChartViewAddApprover:(ZYCTeaLeaveFlowChartModel *)model{
    ZYCWeakSelf
    ZYCTeaLeaveApproverViewController *vc = [[ZYCTeaLeaveApproverViewController alloc] init];
    vc.model = model;
    NSMutableArray *temp = [NSMutableArray array];
    vc.selectApproverBlock = ^(NSMutableArray<ZYCTeaLeaveApplyUserModel *> * _Nonnull appvoers) {
        for (ZYCTeaLeaveApplyUserModel *m in appvoers) {
            m.nodeType = @"3";
            [temp addObject:m.userId];
        }
        self.toUsers = temp;
        for (ZYCTeaLeaveFlowChartModel *model in self.footerDataSource) {
            if ([model.nodeType  integerValue] == 3) { // 下一审批节点
                model.applyUserList = appvoers;
            }
        }
        weakSelf.flowChartView.dataSource = weakSelf.footerDataSource;
        [weakSelf.flowChartView reload];
    };
    [self.navigationController pushViewController:vc animated:YES];
}

// 删除审批人
- (void)teaLeaveRecordFlowChartViewDeleteApprover:(ZYCTeaLeaveApplyUserModel *)m{
    [self.toUsers removeObject:m.userId];
}


#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
    if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:@"public.image"]) {
        TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
        [tzImagePickerVc showProgressHUD];
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        NSDictionary *meta = [info objectForKey:UIImagePickerControllerMediaMetadata];
        [[TZImageManager manager] savePhotoWithImage:image meta:meta location:self.location completion:^(PHAsset *asset, NSError *error){
            [tzImagePickerVc hideProgressHUD];
            if (error) {
                NSLog(@"图片保存失败 %@",error);
            } else {
                TZAssetModel *assetModel = [[TZImageManager manager] createModelWithAsset:asset];
                [self refreshCollectionViewWithAddedAsset:assetModel.asset image:image];
            }
        }];
    }
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)refreshCollectionViewWithAddedAsset:(PHAsset *)asset image:(UIImage *)image {
    NSMutableArray *assetArray = [NSMutableArray array];
    NSMutableArray *imageArray = [NSMutableArray array];
    [assetArray addObject:asset];
    [imageArray addObject:image];
    self.selectedAssets = assetArray;
    self.selectedPhotos = imageArray;
    
}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - ZYCTeaLeaveApplicationBottomViewDelegate
- (void)clickComfirmAction:(UIButton *)sender{
    sender.enabled = NO;
    [self clickComfirmTeaLeave:sender];
}



- (void)clickComfirmTeaLeave:(UIButton *)sender{
    self.updateImageCount = 0;
    self.updateImageResults = [NSMutableArray arrayWithCapacity:0];
    if (self.selectedPhotos.count > 0) {
        for (UIImage *image in self.selectedPhotos) {
            self.updateImageCount ++;
            [self uploadWithImage:image];
        }
    }else{
        [self postTeaLeave:sender];
    }
}
    
#pragma mark - setters
- (void)setLeaveStartTime:(NSString *)leaveStartTime{
    _leaveStartTime = leaveStartTime;
    
    if (self.leaveEndTime) {
        [self getLeaveDaysWithStartTime:leaveStartTime endTime:self.leaveEndTime];
    }
}

- (void)setLeaveEndTime:(NSString *)leaveEndTime{
    _leaveEndTime = leaveEndTime;
    if (self.leaveStartTime) {
        [self getLeaveDaysWithStartTime:self.leaveStartTime endTime:leaveEndTime];
    }
}

- (void)setPostName:(NSString *)postName{
    _postName = postName;
    if (self.leaveStartTime && self.leaveEndTime) {
        [self getLeaveDaysWithStartTime:self.leaveStartTime endTime:self.leaveEndTime];
    }
}

#pragma mark - getters


- (ZYCSelectAmPmDateView *)startDatePickerView {
    ZYCWeakSelf
    if (!_startDatePickerView) {
        _startDatePickerView = [[ZYCSelectAmPmDateView alloc] init];
        _startDatePickerView.tipString = @"请选择开始时间";
        _startDatePickerView.comfirmAction = ^(NSString * _Nonnull dateStr) {
            weakSelf.leaveStartTime = dateStr;
            NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:3];
            [weakSelf.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
        };
        [self.navigationController.view addSubview:_startDatePickerView];
    }
    return _startDatePickerView;
}

- (ZYCSelectAmPmDateView *)endDatePickerView {
    ZYCWeakSelf
    if (!_endDatePickerView) {
        _endDatePickerView = [[ZYCSelectAmPmDateView alloc] init];
        _endDatePickerView.tipString = @"请选择结束时间";
        _endDatePickerView.comfirmAction = ^(NSString * _Nonnull dateStr) {
            
            int a = [NSString junc_CompareOneDateStr:[weakSelf.leaveStartTime substringToIndex:10] withAnotherDateStr:[dateStr substringToIndex:10]];
            if (a < 0) {
                [MrjToast makeToast:@"结束时间不能小于开始时间" makeView:weakSelf.view];
                return;
            }
            
            weakSelf.leaveEndTime = dateStr;
            NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:4];
            [weakSelf.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
 
        };
        [self.navigationController.view addSubview:_endDatePickerView];
    }
    return _endDatePickerView;
}

- (ZYCCommonSelectObjectPickerView *)deptPickerView {
    if (!_deptPickerView) {
        _deptPickerView = [[ZYCCommonSelectObjectPickerView alloc] init];
        _deptPickerView.tipString = @"请选择所属部门";
        _deptPickerView.dataSource = self.deptArray;
        _deptPickerView.delegate = self;
        [self.navigationController.view addSubview:_deptPickerView];
    }
    return _deptPickerView;
}

- (NSArray *)deptArray {
    if (!_deptArray) {
        _deptArray = [[NSArray alloc] init];
    }
    return _deptArray;
}

- (ZYCCommonSelectObjectPickerView *)postPickerView {
    if (!_postPickerView) {
        _postPickerView = [[ZYCCommonSelectObjectPickerView alloc] init];
        _postPickerView.tipString = @"请选择所属岗位";
        _postPickerView.delegate = self;
        [self.navigationController.view addSubview:_postPickerView];
    }
    return _postPickerView;
}

- (NSArray *)postArray {
    if (!_postArray) {
        _postArray = [[NSArray alloc] init];
    }
    return _postArray;
}

- (ZYCCommonSelectObjectPickerView *)leaveTypePickerView {
    if (!_leaveTypePickerView) {
        _leaveTypePickerView = [[ZYCCommonSelectObjectPickerView alloc] init];
        _leaveTypePickerView.tipString = @"请选择请假类型";
        _leaveTypePickerView.dataSource = self.leaveTypeArray;
        _leaveTypePickerView.delegate = self;
        [self.navigationController.view addSubview:_leaveTypePickerView];
    }
    return _leaveTypePickerView;
}

- (NSArray *)leaveTypeArray {
    if (!_leaveTypeArray) {
        _leaveTypeArray = [[NSArray alloc] init];
    }
    return _leaveTypeArray;
}

- (NSArray *)dataSource {
    if (!_dataSource) {
        _dataSource = @[
            @{@"title":@"*所属部门:",@"placeHolder":@"请选择所属部门"},
            @{@"title":@"*所属岗位:",@"placeHolder":@"请选择所属岗位"},
            @{@"title":@"*请假类型:",@"placeHolder":@"请选择请假类型"},
            @{@"title":@"*开始时间:",@"placeHolder":@"请选择开始时间"},
            @{@"title":@"*结束时间:",@"placeHolder":@"请选择结束时间"},
            @{@"title":@"*结束时长(天):",@"placeHolder":@"自动生成"},
            @{@"title":@"请假事由",@"placeHolder":@"请输入"},
            @{@"title":@"上传图片",@"placeHolder":@""},
        ];
    }
    return _dataSource;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kNavBarAndStatusBarHeight, kScreenWidth, kScreenHeight - kNavBarAndStatusBarHeight - 80.0f) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = HEX_RGB(@"#FAFAFA");
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[ZYCTeaLeaveRequiredCell class] forCellReuseIdentifier:NSStringFromClass([ZYCTeaLeaveRequiredCell class])];
        [_tableView registerClass:[ZYCTeaLeaveOptionalCell class] forCellReuseIdentifier:NSStringFromClass([ZYCTeaLeaveOptionalCell class])];
        [_tableView registerClass:[ZYCTeaLeaveAddPhotoCell class] forCellReuseIdentifier:NSStringFromClass([ZYCTeaLeaveAddPhotoCell class])];
        _tableView.showsVerticalScrollIndicator = NO;
    }
    return _tableView;
}


- (NSArray *)footerDataSource {
    if (!_footerDataSource) {
        _footerDataSource = [[NSArray alloc] init];
    }
    return _footerDataSource;
}

- (ZYCTeaLeaveRecordFlowChartView *)flowChartView {
    if (!_flowChartView) {
        _flowChartView = [[ZYCTeaLeaveRecordFlowChartView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50.0f)];
        _flowChartView.type = ZYCTeaLeaveFlowChartApplication;
        _flowChartView.delegate = self;
    }
    return _flowChartView;
}
- (ZYCTeaLeaveApplicationBottomView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[ZYCTeaLeaveApplicationBottomView alloc] initWithFrame:CGRectMake(0, kScreenHeight - 80.0f, kScreenWidth, 80.0f)];
//        _bottomView.delegate = self;
        [_bottomView.comfirmButton addTarget:self action:@selector(clickComfirmAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _bottomView;
}

- (NSMutableArray *)toUsers {
    if (!_toUsers) {
        _toUsers = [NSMutableArray arrayWithCapacity:0];
    }
    return _toUsers;
}

- (NSArray *)copyUsers {
    if (!_copyUsers) {
        _copyUsers = [[NSArray alloc] init];
    }
    return _copyUsers;
}
- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        // set appearance / 改变相册选择页的导航栏外观
        _imagePickerVc.navigationBar.barTintColor = self.navigationController.navigationBar.barTintColor;
        _imagePickerVc.navigationBar.tintColor = self.navigationController.navigationBar.tintColor;
        UIBarButtonItem *tzBarItem, *BarItem;
        if (@available(iOS 9, *)) {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
            BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        } else {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil];
            BarItem = [UIBarButtonItem appearanceWhenContainedIn:[UIImagePickerController class], nil];
        }
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
 
    }
    return _imagePickerVc;
}


#pragma mark - private method

- (void)pushTZImagePickerViewController{
    ZYCWeakSelf
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 columnNumber:5 delegate:self pushPhotoPickerVc:YES];
    if (self.selectedAssets.count > 0) {
        imagePickerVc.selectedAssets = self.selectedAssets;
    }
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        weakSelf.selectedPhotos = [NSMutableArray arrayWithArray:photos];
        weakSelf.selectedAssets = [NSMutableArray arrayWithArray:assets];

    }];
    
    imagePickerVc.barItemTextColor = [UIColor blackColor];
    [imagePickerVc.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor blackColor]}];
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.navigationBar.tintColor = [UIColor blackColor];
    imagePickerVc.naviBgColor = [UIColor whiteColor];
    imagePickerVc.navigationBar.translucent = NO;
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

- (void)setSelectedAssets:(NSMutableArray *)selectedAssets{
    _selectedAssets = selectedAssets;
    
    
    
}

- (void)setSelectedPhotos:(NSMutableArray *)selectedPhotos{
    _selectedPhotos = selectedPhotos;
    NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:7];
    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
 
}

#pragma mark - 网络请求
// 获取部门列表
- (void)getDeptList{
    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] getUrlString:Appliance_Get_DeptList requestService:RequestServiceActiviti parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            [MrjSVProgressHUD dismiss];
            if (SUCCESS(responseObject[@"code"])) {
                NSArray *array = [NSArray yy_modelArrayWithClass:[ZYCCommonBaseModel class] json:responseObject[@"body"]];
                self.deptArray = array;
            }else{
                [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}

// 根据部门id获取岗位列表
- (void)getPostListByDeptId:(NSString *)deptId{
    NSDictionary *params = @{
        @"deptId":deptId
    };
    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] getUrlString:Appliance_Get_PostList requestService:RequestServiceActiviti parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            [MrjSVProgressHUD dismiss];
            if (SUCCESS(responseObject[@"code"])) {
                NSArray *array = [NSArray yy_modelArrayWithClass:[ZYCCommonBaseModel class] json:responseObject[@"body"]];
                self.postArray = array;
                self.postPickerView.dataSource = self.postArray;
                [self.postPickerView reload];
                
  
                
            }else{
                [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}

- (void)getLeaveTypeArray{
    [[URLManager sharedURLManager] getUrlString:Appliance_Get_LeaveTypeList requestService:RequestServiceActiviti parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            if (SUCCESS(responseObject[@"code"])) {
                NSArray *array = [NSArray yy_modelArrayWithClass:[ZYCCommonBaseModel class] json:responseObject[@"body"]];
                self.leaveTypeArray = array;
            }else{
                [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}

- (void)getLeaveDaysWithStartTime:(NSString *)startTime endTime:(NSString *)endTime{
    if (self.postName.length == 0) {
        [MrjToast makeToast:@"请选择岗位" makeView:self.view];
        return;
    }
    [self getLeaveTotalTime];
    
}

// 获取流程节点以及相关参数
- (void)getLeaveTotalTime{
    NSDictionary *params = @{
        @"postName":self.postName,
        @"leaveStartTime":self.leaveStartTime,
        @"leaveEndTime":self.leaveEndTime
    };
    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_ProcessList requestService:RequestServiceActiviti parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            [MrjSVProgressHUD dismiss];
            if (SUCCESS(responseObject[@"code"])) {
                
                NSArray *array = [NSArray yy_modelArrayWithClass:[ZYCTeaLeaveFlowChartModel class] json:responseObject[@"body"][@"nodeList"]];
                NSMutableArray *tmp = [NSMutableArray arrayWithCapacity:0];
                for (ZYCTeaLeaveFlowChartModel *model in array) {
                    
                    if ([model.nodeType integerValue] == 3) {
                        [model.applyUserList removeAllObjects];
                    }

                    model.isShow = YES;

                    if ([model.nodeType  integerValue] == 4) {// 抄送人节点
                        if ([model.applyUserList isKindOfClass:[NSArray class]] && model.applyUserList.count > 0) {
                            for (ZYCTeaLeaveApplyUserModel *m in model.applyUserList) {

                                [tmp addObject:m.userId];
                            }
                        }
 
                    }
                }
                self.copyUsers = tmp.copy;//抄送人
                self.flowChartView.frame = CGRectMake(0, 0, kScreenWidth, 120.0f * array.count + 50.0f);
                
                ZYCTeaLeaveFlowChartModel *last = array.lastObject;
                last.isShow = NO;
                self.footerDataSource = array;
                self.flowChartView.dataSource = self.footerDataSource;
                [self.flowChartView reload];
                self.leaveDays = [NSString stringWithFormat:@"%@",responseObject[@"body"][@"leaveDays"]];
                self.processDefinitionKey = responseObject[@"body"][@"processDefinitionKey"];
                NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:5];
                [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];

            }else{
                [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}
- (void)postTeaLeave:(UIButton *)sender{
    if (self.updateImageCount != 0) {// 防止发布多条
        return;
    }
    
    if (self.deptId.length == 0 || self.deptName.length == 0) {
        [MrjToast makeToast:@"请选择部门" makeView:self.view];
        sender.enabled = YES;
        return;
    }
    
    if (self.postId.length == 0 || self.postName.length == 0) {
        [MrjToast makeToast:@"请选择岗位" makeView:self.view];
        sender.enabled = YES;
        return;
    }
    
    if (self.leaveTypeId.length == 0) {
        [MrjToast makeToast:@"请选择请假类型" makeView:self.view];
        sender.enabled = YES;
        return;
    }
    
    if (self.leaveStartTime.length == 0) {
        [MrjToast makeToast:@"请选择开始时间" makeView:self.view];
        sender.enabled = YES;
        return;
    }
    
    if (self.leaveEndTime.length == 0) {
        [MrjToast makeToast:@"请选择结束时间" makeView:self.view];
        sender.enabled = YES;
        return;
    }
    
    if (self.toUsers.count == 0) {
        [MrjToast makeToast:@"请选择下一节点审批人" makeView:self.view];
        sender.enabled = YES;
        return;
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    // 必传参数
    [params setObject:self.deptId forKey:@"deptId"];
    [params setObject:self.deptName forKey:@"deptName"];
    [params setObject:self.postId forKey:@"postId"];
    [params setObject:self.postName forKey:@"postName"];
    [params setObject:self.leaveTypeId forKey:@"leaveType"];
    [params setObject:self.leaveStartTime forKey:@"leaveStartTime"];
    [params setObject:self.leaveEndTime forKey:@"leaveEndTime"];
    [params setObject:self.leaveDays forKey:@"leaveDays"];
    [params setObject:[self.toUsers componentsJoinedByString:@","] forKey:@"toUsers"];
    [params setObject:self.processDefinitionKey forKey:@"processDefinitionKey"];
    

    // 可选参数
    if (self.leaveReason.length > 0) {
        [params setObject:self.leaveReason forKey:@"leaveReason"];
    }

    if (self.copyUsers.count > 0) {
        [params setObject:[self.copyUsers componentsJoinedByString:@","] forKey:@"copyUsers"];
    }

    if (self.updateImageResults.count > 0) {
        [params setObject:[self.updateImageResults yy_modelToJSONObject]  forKey:@"files"];
    }
    NSLog(@"传参:====%@",params);
    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_TeacherLeaveAdd requestService:RequestServiceActiviti parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            sender.enabled = YES;
            [MrjSVProgressHUD dismiss];
            if (SUCCESS(responseObject[@"code"])) {
                [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });

            }
        } failure:^(NSError * _Nonnull error) {
            sender.enabled = YES;
        }];
}

- (void)uploadWithImage:(UIImage *)image{
    NSString *urlStr = [NSString stringWithFormat:@"%@/zd-system-service/%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"sdfz_url"],Common_Post_Upload];
    [[URLManager sharedURLManager] POST:urlStr parameters:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSString *fileName;
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        formatter.dateFormat = @"MMddHHmmss";
        NSString *dateString = [formatter stringFromDate:[NSDate date]];
        fileName = [NSString stringWithFormat:@"%@.png",dateString];//以这种格式防止上传的图片重复覆盖
        NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/png"];
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (SUCCESS(responseObject[@"code"])) {
                self.updateImageCount --;
                ZYCFileCommonModel *model = [[ZYCFileCommonModel alloc] init];
                model.filePath = responseObject[@"body"][@"url"];
                model.fileName = responseObject[@"body"][@"fileName"];
                [self.updateImageResults addObject:model];
                [self postTeaLeave:self.bottomView.comfirmButton];
            }else{
                [MrjToast makeToast:@"图片上传失败" makeView:self.view];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        }];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
